package com.supor.aiot.home.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.GridItemDecoration;
import com.supor.aiot.common.utils.AnimationUtil;
import com.supor.aiot.home.R;
import com.supor.aiot.home.ui.device.config.InputWiFiActivity;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Objects;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: PopUtils <br>
 * 作者: lei <br>
 * 日期: 2020/12/28 <br>
 */
public class AddDevicePop {

    static PopupWindow popupWindow;
    Handler handler;
    private WeakReference<Fragment> fragmentReference;
    private WeakReference<Activity> activityReference;

    private static volatile AddDevicePop instance;
    private float alpha;
    int duration = 300;
    int sleepTime = duration / 100;
    Button popCancel;
    private RecyclerView rcvDevice;

    public static AddDevicePop getInstance() {
        if (instance == null) {
            instance = new AddDevicePop();
        }
        return instance;
    }

    private AddDevicePop() {
    }

    public void initAddDevicePop(Fragment fragment) {
        fragmentReference = new WeakReference<>(fragment);
        initAddDevicePop(fragment.getActivity());
    }

    public void initAddDevicePop(Activity activity) {
        activityReference = new WeakReference<>(activity);
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_add_device, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.popup_window_anim);

        rcvDevice = view.findViewById(R.id.rcv_product);
        // 设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, 3);
        rcvDevice.setLayoutManager(gridLayoutManager);
        rcvDevice.setOverScrollMode(View.OVER_SCROLL_NEVER);
        rcvDevice.setNestedScrollingEnabled(false);
        rcvDevice.addItemDecoration(new GridItemDecoration(ContextCompat.getColor(activity,
                R.color.transparent), activity.getResources().getDimensionPixelSize(R.dimen.dp_4),
                activity.getResources().getDimensionPixelSize(R.dimen.dp_4), -1));

        popCancel = view.findViewById(R.id.pop_cancel);

        popCancel.setOnClickListener(v -> popupWindow.dismiss());
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(() -> ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        }));
    }

    public void setDeviceList(List<ProductType.ProductModel> list) {
        // 设置适配器
        BaseQuickAdapter<ProductType.ProductModel, BaseViewHolder> quickAdapter =
                new BaseQuickAdapter<ProductType.ProductModel, BaseViewHolder>(R.layout.item_device, list) {
                    @Override
                    protected void convert(@NotNull BaseViewHolder holder, ProductType.ProductModel data) {
                        if ("EPC".equalsIgnoreCase(data.modelTypeId)) {
                            holder.setImageResource(R.id.iv_image, R.mipmap.ic_device_chief_machine);
                        } else if ("ZKQD".equalsIgnoreCase(data.modelTypeId)) {
                            holder.setImageResource(R.id.iv_image, R.mipmap.ic_device_oven);
                        }
                        holder.setText(R.id.tv_name, data.modelTypeName);
                    }
                };
        // DeviceAdapter quickAdapter = new DeviceAdapter(list);
        rcvDevice.setAdapter(quickAdapter);
        quickAdapter.setOnItemClickListener((adapter1, view, position) -> {
            Logc.e("onItemClick: position: " + position);

            List<ProductType.ProductModel> list1 = quickAdapter.getData();
            ProductType.ProductModel device = list1.get(position);
            Intent intent = new Intent(activityReference.get(), InputWiFiActivity.class);
            intent.putExtra(Constants.Key.PRODUCT_MODEL, device);
            Objects.requireNonNull(fragmentReference.get().getActivity()).startActivityForResult(intent, Constants.REQUEST_CODE);
            dismissNFCPop();
        });
    }

    public void showAddDevicePop(Activity activity, View rootView) {
        if (popupWindow == null) {
            initAddDevicePop(activity);
        } else {
            popCancel.setVisibility(View.VISIBLE);
        }
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isNFCPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void touchSuccess() {
        // tvDialogTip1.setVisibility(View.VISIBLE);
        popCancel.setVisibility(View.INVISIBLE);
        handler.postDelayed(this::dismissNFCPop, 1000);
    }

    public void dismissNFCPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
}
